package com.self.console.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by pc on 2015/1/4.
 */
public class TemplateUtil {

    private final static Logger LOG = LoggerFactory.getLogger(TemplateUtil.class);

    final static int BUFFER_SIZE = 4096;

    /**
     * 下载网络资源
     *
     * @param file 待下载文件路径 http路径
     */
    public static String downloadFile(String file) {
        try {
            URL url = new URL(file);
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();

            byte[] buffer = new byte[BUFFER_SIZE];

            int count = -1;
            while((count = inStream.read(buffer,0,BUFFER_SIZE)) != -1)
                outStream.write(buffer, 0, count);

            buffer = null;
            return new String(outStream.toByteArray(),"UTF-8");

        } catch (Exception e) {
            LOG.error("下载模板"+file+"失败！",e);
        }

        return null;
    }

    public static String collectHtml(String selector,String path,String url){

        Document doc=null;
        try {
            doc = Jsoup.connect(url).timeout(5000).get();
            Element element = doc.select(selector).first();
            return element.html();
        } catch (Exception e) {
            LOG.error("打开页面[" + url + "]失败！", e);
        }

        return null;
    }

}
